<template>
  <div>

    <!-- 表单 -->
    <el-form size="small" :model="form" :inline="true">
      <el-form-item label="角色名称" style="font-weight:bold;">
        <el-input v-model="form.roleName" placeholder="请输入角色名称" style="width:200px;" clearable></el-input>
      </el-form-item>
      <el-form-item label="状态" style="font-weight:bold;">
        <el-select v-model="form.status" placeholder="请选择状态" style="width:200px;" clearable>
          <el-option label="正常" value="0"></el-option>
          <el-option label="停用" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-button size="small" class="search_button" type="primary" icon="el-icon-search"
        @click="getRoleList">查询</el-button>
      <el-button size="small" plain class="reset_button" icon="el-icon-refresh" @click="reset">重置</el-button>
    </el-form>
    <!-- 表单 -->
    <el-row>
      <el-button size="small" type="primary" icon="el-icon-folder-add" @click="showAddRole">新增</el-button>
      <el-button size="small" plain icon="el-icon-setting" @click="showPowerEdit">权限设置</el-button>
    </el-row>

    <!-- <el-divider></el-divider> -->
    <!-- 表格 -->
    <el-table size="medium" ref="multipleTable" :data="tableData" @selection-change="handleSelectionChange"
      style="width: 100%;margin-top:10px" border>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="roleName" label="角色名称" align="center"></el-table-column>
      <el-table-column prop="roleSort" label="显示顺序" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" align="center">
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">正常</span>
          <span v-if="scope.row.status == 1">停用</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" align="center"></el-table-column>
      <el-table-column prop="handle" label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" plain @click="showChangeRole(scope.row)">修改</el-button>
          <!-- <el-button size="mini" type="danger" plain @click="deleteRole({ id: scope.row.id })">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加修改角色弹窗 -->
    <el-drawer :title="title" :visible.sync="drawer" direction="rtl">
      <el-form :model="formNew" :rules="rules" ref="ruleForm" label-width="100px" size="small">
        <el-form-item label="角色名称 :" prop="roleName">
          <el-input v-model="formNew.roleName" placeholder="请输入角色名称" style="width:330px" clearable></el-input>
        </el-form-item>
        <el-form-item label="角色顺序 :" prop="roleSort">
          <el-input-number v-model="formNew.roleSort" controls-position="right" :min="0" style="width:260px" clearable />
        </el-form-item>
        <el-form-item label="状态" v-show="formNew.status">
          <el-radio-group v-model="formNew.status" clearable>
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注 :">
          <el-input v-model="formNew.remark" type="textarea" placeholder="请输入备注" style="width:330px" clearable></el-input>
        </el-form-item>
      </el-form>
      <div class="btnBox">
        <el-button class="btnBox_item" type="primary" @click="submit('ruleForm')">确 定</el-button>
        <el-button class="btnBox_item" @click="drawer = false">取 消</el-button>
      </div>
    </el-drawer>

    <!-- 权限设置弹窗 -->
    <el-dialog title="权限设置" :visible.sync="powerEdit" width="34%">
      <el-tabs v-model="activeName">
        <el-tab-pane label="PC端权限" name="PC">
          <el-form :model="formPower" :rules="rules" label-width="100px" size="small">
            <el-form-item label="菜单权限 :">
              <el-checkbox v-model="menuExpand" @change="handleCheckedTreeExpand($event, 'menuPC')">展开/折叠</el-checkbox>
              <el-checkbox v-model="menuNodeAll" @change="handleCheckedTreeNodeAll($event, 'menuPC')">全选/全不选</el-checkbox>
              <el-checkbox v-model="menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menuPC')">父子联动</el-checkbox>
              <el-tree class="tree-border" :data="menuOptionsPC" show-checkbox ref="menuPC" node-key="id"
                :check-strictly="!menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="小程序权限" name="Mobile">
          <el-form :model="formPower" :rules="rules" label-width="100px" size="small">
            <el-form-item label="菜单权限 :">
              <el-checkbox v-model="menuExpand"
                @change="handleCheckedTreeExpand($event, 'menuMobile')">展开/折叠</el-checkbox>
              <el-checkbox v-model="menuNodeAll"
                @change="handleCheckedTreeNodeAll($event, 'menuMobile')">全选/全不选</el-checkbox>
              <el-checkbox v-model="menuCheckStrictly"
                @change="handleCheckedTreeConnect($event, 'menuMobile')">父子联动</el-checkbox>
              <el-tree class="tree-border" :data="menuOptionsMobile" show-checkbox ref="menuMobile" node-key="id"
                :check-strictly="!menuCheckStrictly" empty-text="加载中，请稍候" :props="defaultProps"></el-tree>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <div>
        <el-button size="small" type="primary" @click="comfirmPower">确 定</el-button>
        <el-button size="small" @click="powerEdit = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-pagination class="pagination" background layout="total, sizes, prev, pager, next, jumper" :total="total"
      :page-size="10" :page-sizes="[10, 20, 30, 40]" @current-change="handleCurrentChange"
      @size-change="handleSizeChange"></el-pagination>
  </div>
</template>

<script>
import {
  getRoleList,
  addNewRole, //添加角色
  changeRole, //修改角色
  deleteRole, //删除角色
  saveRoleMenu,//设置角色菜单权限
  getMenuByRoleId,//根据角色Id获取菜单Id列表
} from '_api/RoleManage/index.js'
import { getMenuList } from '_api/MenuManage/index.js'

export default {
  data() {
    return {
      activeName: 'PC',
      powerEdit: false,
      drawer: false,
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 菜单列表
      menuOptionsPC: [],
      menuOptionsMobile: [],
      // 父子联动
      menuCheckStrictly: true,
      // 展开/折叠
      menuExpand: false,
      // 全选/全不选
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      form: {
        current: 0,
        field: "",
        order: "",
        pageSize: 10,
        roleName: "",
        status: ""
      },
      formNew: {
        remark: "",
        roleName: "",
        roleSort: ""
      },
      rules: {
        roleName: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
        ],
        roleSort: [
          { required: true, message: "角色顺序不能为空", trigger: "blur" }
        ]
      },
      tableData: [],
      title: "",
      total: 0,
      // 查询参数
      queryParams: {
        component: "",
        current: 0,
        field: "",
        hidden: "",
        icon: "",
        id: "",
        keepAlive: "",
        name: "",
        order: "",
        pageSize: 100,
        parentId: "",
        path: "",
        perms: "",
        redirect: "",
        sortIndex: "",
        title: "",
        type: ""
      },
      formPower: {
        menuIds: [],
        roleId: ""
      },
      multipleSelection: []
    }
  },
  methods: {
    // 树权限（展开/折叠）
    handleCheckedTreeExpand(value, type) {
      if (type == 'menuPC') {
        let treeList = this.menuOptionsPC;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menuPC.store.nodesMap[treeList[i].id].expanded = value;
        }
      } else if (type == 'menuMobile') {
        let treeList = this.menuOptionsMobile;
        for (let i = 0; i < treeList.length; i++) {
          this.$refs.menuMobile.store.nodesMap[treeList[i].id].expanded = value;
        }
      }
    },
    // 树权限（全选/全不选）
    handleCheckedTreeNodeAll(value, type) {
      if (type == 'menuPC') {
        this.$refs.menuPC.setCheckedNodes(value ? this.menuOptionsPC : []);
      } else if (type == 'menuMobile') {
        this.$refs.menuMobile.setCheckedNodes(value ? this.menuOptionsMobile : []);
      }
    },
    // 树权限（父子联动）
    handleCheckedTreeConnect(value, type) {
      if (type == 'menuPC') {
        this.menuCheckStrictly = value ? true : false;
      } else if (type == 'menuMobile') {
        this.menuCheckStrictly = value ? true : false;
      }
    },
    // 所有菜单节点数据
    getMenuAllCheckedKeys() {
      // 目前被选中的菜单节点
      let checkedKeys = this.$refs.menu.getCheckedKeys();
      // 半选中的菜单节点
      let halfCheckedKeys = this.$refs.menu.getHalfCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    // 新增弹窗
    showAddRole() {
      this.resetForm();
      this.drawer = true
      this.title = "新增角色"
    },
    // 修改弹窗
    showChangeRole(row) {
      this.resetForm();
      this.drawer = true
      this.title = "修改角色"
      console.log(row);
      this.formNew = row
    },
    // 提交
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formNew.id) {
            changeRole(this.formNew).then(res => {
              if (res.data.success == true) {
                this.drawer = false
                this.$message({
                  message: '修改成功!',
                  duration: 1000,
                  type: 'success',
                  onClose: () => {
                    this.reset()
                  }
                })
              } else {
                this.$message(res.data.message)
              }
            })
          } else {
            // console.log(this.getMenuAllCheckedKeys());
            addNewRole(this.formNew).then(res => {
              if (res.data.success == true) {
                this.drawer = false
                this.$message({
                  message: '添加成功!',
                  duration: 1000,
                  type: 'success',
                  onClose: () => {
                    this.reset()
                  }
                })
              } else {
                this.$message(res.data.message)
              }
            })
          }
        } else {
          return false;
        }
      });
    },
    // 删除角色
    deleteRole(e) {
      this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteRole(e).then(res => {
          if (res.data.success == true) {
            this.$message({
              message: '删除成功!',
              duration: 1000,
              type: 'success',
              onClose: () => {
                this.reset()
              }
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    resetForm() {
      this.formNew = {
        remark: "",
        roleName: "",
        roleSort: ""
      }
    },
    reset() {
      this.form = {
        current: 0,
        field: "",
        order: "",
        pageSize: 10,
        roleName: "",
        status: ""
      }
      this.getRoleList()
    },
    handleCurrentChange(e) {
      //当前页
      this.form.current = e
      this.getRoleList()
    },
    handleSizeChange(e) {
      this.form.pageSize = e
      this.getRoleList()
    },
    //查询角色信息列表
    getRoleList() {
      getRoleList(this.form).then(res => {
        // console.log(res)
        if (res.data.success == true) {
          this.tableData = res.data.data.list
          this.total = res.data.data.total
        } else {
          this.$message.info(res.data.message)
        }
      }).catch(error => {
        // console.log(error.response.status);
        // if (error.response.status == 401) {
        //   this.$confirm('登录状态过期, 请重新登录!', '提示', {
        //     confirmButtonText: '确定',
        //     // cancelButtonText: '取消',
        //     showCancelButton: false,
        //     type: 'warning'
        //   }).then(() => {
        //     this.$router.push('/login')
        //   }).catch(() => {

        //   })
        // }
      })
    },
    //查询菜单列表
    // getMenuList() {
    //   getMenuList(this.queryParams).then(res => {
    //     if (res.data.success == true) {
    //       this.menuOptions = res.data.data.list
    //     }
    //   })
    // },
    // 权限设置弹窗
    showPowerEdit() {
      if (this.multipleSelection.length == 0) {
        this.$message.warning("只能选择一条数据!")
      } else if (this.multipleSelection.length == 1) {
        this.powerEdit = true
        this.queryParams.type = '0'
        getMenuList(this.queryParams).then(res => {
          if (res.data.success == true) {
            this.menuOptionsPC = res.data.data.list
            this.queryParams.type = '4'
            getMenuList(this.queryParams).then(res => {
              this.menuOptionsMobile = res.data.data.list
            })
          }
        })
        getMenuByRoleId({ roleId: this.formPower.roleId }).then(res => {
          this.$refs.menuPC.setCheckedKeys(res.data.data);
          this.$refs.menuMobile.setCheckedKeys(res.data.data);
        })
      } else if (this.multipleSelection.length > 1) {
        this.$message.warning("只能选择一条数据!")
      }
    },
    handleSelectionChange(val) {
      console.log(val);
      this.multipleSelection = val
      if (val.length == 1) {
        this.formPower.roleId = val[0].id
      }
      // console.log(this.formPower.roleId);
    },
    comfirmPower() {
      console.log(this.$refs.menuPC.getCheckedKeys());
      console.log(this.$refs.menuMobile.getCheckedKeys());
      this.formPower.menuIds = this.$refs.menuPC.getCheckedKeys().concat(this.$refs.menuMobile.getCheckedKeys())
      console.log(this.formPower.menuIds);
      saveRoleMenu(this.formPower).then(res => {
        if (res.data.success == true) {
          this.$message.success("操作成功!")
          this.powerEdit = false
          this.reset()
        }
      })
    }
  },
  created() {
    this.getRoleList()
  },
};
</script>
<style lang="scss" scoped>
.pagination {
  float: right;
  margin-top: 10px;
}

.search_button {
  margin-left: 80px;
}

.reset_button {
  margin-left: 10px;
}

/* tree border */
.tree-border {
  width: 80%;
  margin-top: 5px;
  border: 1px solid #e5e6e7;
  background: #FFFFFF none;
  border-radius: 4px;
}

.btnBox {
  display: flex;
  width: 410px;
  justify-content: space-between;
  position: relative;
  left: calc(50% - 205px);
  padding-bottom: 20px;
}

.btnBox_item {
  width: 200px;
}
</style>
